package com.goldenautumn.prefabricate.activity.cart

import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.VibrateUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.category.CategoryLayoutAdapter
import com.goldenautumn.prefabricate.activity.mall.GoodsDetailsActivity
import com.goldenautumn.prefabricate.activity.search.GoodsLayoutAdapter
import com.goldenautumn.prefabricate.business.entity.CarGoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.SearchParams
import com.goldenautumn.prefabricate.business.mall.CarDataUiState
import com.goldenautumn.prefabricate.business.mall.GoodsInfoUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.databinding.FragmentCartBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.isLogin
import com.goldenautumn.prefabricate.utils.numberFormat
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseFragment
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visible
import qncx.external.common.utils.intent
import qncx.external.common.widget.dialog.PromptDialog

class CartFragment : BaseFragment<FragmentCartBinding>(), CarGoodsAdapter.OnNumberChangeListener {

    private val mMallModel by viewModels<MallViewModel>()

    private val mRecommendedAdapter by lazy {
        CategoryLayoutAdapter()
    }

    private val mGoodsAdapter by lazy {
        CarGoodsAdapter()
    }

    var isAll = false

    override fun getLayoutId(): Int = R.layout.fragment_cart

    override suspend fun initView() {
//        ImmersionBar.setTitleBar(this, mBinding.toolbar)

        mBinding.carRv.layoutManager = LinearLayoutManager(mContext)
        mBinding.recommendedRv.layoutManager = GridLayoutManager(mContext,2)
        mBinding.carRv.adapter = mGoodsAdapter
        (mBinding.carRv.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mBinding.recommendedRv.adapter = mRecommendedAdapter
        mGoodsAdapter.setStateViewLayout(mContext,R.layout.recycler_empty_view)
        var emptyTv = mGoodsAdapter.stateView?.findViewById<TextView>(R.id.prompt_content)
        emptyTv?.setCompoundDrawablesWithIntrinsicBounds(null,ContextCompat.getDrawable(mContext, R.mipmap.ic_empty_data), null, null)
        emptyTv?.text = getString(R.string.no_car_goods)
        mGoodsAdapter.mOnNumberChangeListener = this
        mGoodsAdapter.isStateViewEnable = true

        mBinding.actionBtn.setOnClickListener {
            if(mGoodsAdapter.items.isEmpty()) {
                (activity as MainActivity).goHome(0)
                return@setOnClickListener
            }
            var selectGoods = mGoodsAdapter.items.filter { it.isCheck }
            if(selectGoods.isNotEmpty()) {
                var ids = ArrayList<String>()
                selectGoods.forEach { ids.add("${it.goods_id ?: 0}_${it.goods_sku?.spec_sku_id}") }
                startActivity(SettlementActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,ids.joinToString(",")))
            } else {
                VibrateUtils.vibrate(50)
                mBinding.actionBtn.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.shake_anim))
            }
        }

        mBinding.allBtn.setOnClickListener {
            isAll = !isAll
            mGoodsAdapter.items.forEach { it.isCheck = isAll }
            mGoodsAdapter.notifyDataSetChanged()
            onChangeNumber("0")
        }

        mBinding.deleteBtn.setOnClickListener {
            var totalNumber = 0
            mGoodsAdapter.items.forEach {
                if (it.isCheck) totalNumber += it.total_num
            }
            PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
                override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                    view.setTitleText(getString(R.string.remove_product))
                    view.setMsgText(getString(R.string.car_delete_msg))
                    view.setShowCancel(true)
                    view.getPromptConfirm().setOnClickListener {
                        dialog.dismiss()
                        var selectItem = mGoodsAdapter.items.filter { it.isCheck }
                        var specs = ArrayList<String>()
                        selectItem.forEach {
                            specs.add("${it.goods_id}_${it.goods_sku?.spec_sku_id}")
                        }
                        mMallModel.onDeleteCar(specs.joinToString(","),selectItem)
                    }
                }
            }).onShow(childFragmentManager.beginTransaction())
        }

        mBinding.totalPrice.setOnClickListener {
//            CarDiscountDialog(it).onShow(childFragmentManager.beginTransaction())
        }

        mRecommendedAdapter.setOnItemClickListener{adapter,_,position ->
            var item = adapter.getItem(position)
            startActivity(GoodsDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item?.goods_id))
        }

        mMallModel.getGoodsList(SearchParams())

        while (isActive) {
            select {
                mMallModel.goodsDetailsRequests.onReceive {
                    when(it) {
                        is GoodsInfoUiState.GoodsList -> {
                            it.goodsList.shuffle()
                            mRecommendedAdapter.submitList(it.goodsList)
                        }
                        is GoodsInfoUiState.GoodsAddCar -> {
                            it.msg?.let { onCenterToast(it) }
                        }
                        else -> {

                        }
                    }
                }
                mMallModel.carDataReq.onReceive {
                    when(it) {
                        is CarDataUiState.CarList -> {
                            var isAmount = true
                            if(it.data.size == mGoodsAdapter.items.size) {
                                it.data.forEachIndexed { index, item ->
                                    if(item.goods_id != mGoodsAdapter.items[index].goods_id || item.total_num != mGoodsAdapter.items[index].total_num)
                                        isAmount = false
                                }
                            } else isAmount = false
                            if(!isAmount) {
                                mGoodsAdapter.submitList(it.data)
                                setCarGoods()
                                isAll = false
                                mBinding.totalPrice.text = String.format(getString(R.string.currency),"0.00")
                                mBinding.allBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, if(isAll) R.mipmap.ic_car_select else R.mipmap.ic_car_not_select), null, null, null)
                            } else { }
                        }
                        is CarDataUiState.CarDelete -> {
                            if(it.msg == null) {
                                it.deleteData.forEach { mGoodsAdapter.remove(it) }
                                onChangeNumber("0")
                            } else onCenterToast(it.msg)
                        }
                        else -> {

                        }
                    }
                }
            }
        }

    }

    override fun onChangeNumber(ids: String, type: String?,item:CarGoodsInfoVO?) {
        var totalPrice = 0f
        var totalNumber = 0
        isAll = mGoodsAdapter.items.isNotEmpty()
        mGoodsAdapter.items.forEach {
            if (it.isCheck) {
                totalNumber += it.total_num
                totalPrice += (it.total_num * ("${it.goods_sku?.goods_price}").toFloat())
            } else isAll = false
        }
        mBinding.allBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, if(isAll) R.mipmap.ic_car_select else R.mipmap.ic_car_not_select), null, null, null)
        mBinding.totalPrice.text = String.format(getString(R.string.currency),numberFormat("$totalPrice"))
        mBinding.actionBtn.text = (String.format(getString(R.string.car_checkout), "$totalNumber"))
        mBinding.deleteBtn.isVisible(totalNumber > 0)
        if(type != null && item != null){
            if(type == "add"){
                mMallModel.addCar("${item.goods_id}","1","${item.goods_sku?.spec_sku_id}")
            } else {
                mMallModel.subCar("${item.goods_id}","1","${item.goods_sku?.spec_sku_id}")
            }
        }
    }

    fun setCarGoods(){
        mBinding.allBody.isVisible(mGoodsAdapter.items.isNotEmpty())
        mBinding.shapeLinearLayout.isVisible(mGoodsAdapter.items.isNotEmpty())
//        mBinding.actionBtn.shapeBuilder?.setShapeSolidColor(ContextCompat.getColor(mContext,if(mGoodsAdapter.items.isNotEmpty())R.color.colorPrimary else qncx.external.common.R.color.transparent))?.into(mBinding.actionBtn)
//        mBinding.actionBtn.setTextColor(ContextCompat.getColor(mContext,if(mGoodsAdapter.items.isNotEmpty())R.color.white else R.color.colorPrimary))
        mBinding.actionBtn.text = (if(mGoodsAdapter.items.isNotEmpty()) String.format(getString(R.string.car_checkout), "0") else getString(R.string.start_shopping))
    }

    override fun onStart() {
        super.onStart()
        if(isLogin()) mMallModel.getCarList()
        else mGoodsAdapter.submitList(arrayListOf())
    }

}